// ignore_for_file: constant_identifier_names



import 'dart:io';

import 'package:fijkplayer/fijkplayer.dart';
import 'player_platform_interface.dart';

class Player extends FijkPlayer {
  static const asset_url_suffix = "asset:///";

  static String _cachePath = '/storage/emulated/0/Android/data/com.xiangshan.flutter_android_module.host/files';
  bool enableCache = true;
  static void setCachePath (String path) {
    _cachePath = path;
  }

  @override
  Future<void> setDataSource(String path,
      {bool autoPlay = false, bool showCover = false}) async{
    var videoPath = getVideoCatchPath(path, _cachePath);

      // 执行三级缓存的逻辑 - 视频资源一级缓存一版就不涉及了。这里是展开二级三级缓存逻辑；
    if (File(videoPath).existsSync()) {
      // 二级缓存存在，使用本地保存的文件
      path = videoPath;
    } else if(enableCache){
      // 执行三级缓存，并添加缓存文件到二级缓存（本地）
      // 设置1，增加视频path前缀
      path = 'ijkio:cache:ffio:$path'; // 这个是官方给出的视频缓存方案
      const category = FijkOption.formatCategory;
      const key = 'cache_file_path';
      setOption(category, key, videoPath);
    } else {
      // 本地无视频资源，执行三级缓存
    }

    super.setDataSource(path, autoPlay: autoPlay, showCover: showCover);
  }

  void setCommonDataSource(
    String url, {
    SourceType type = SourceType.net,
    bool autoPlay = false,
    bool showCover = false,
  }) {
    if (type == SourceType.asset && !url.startsWith(asset_url_suffix)) {
      url = asset_url_suffix + url;
    }

    setDataSource(url, autoPlay: autoPlay, showCover: showCover);
  }

  Future<String?> getPlatformVersion() {
    return PlayerPlatform.instance.getPlatformVersion();
  }

  String getVideoCatchPath(String url, String cachePath) {
    Uri uri = Uri.parse(url);
    String name = uri.pathSegments.last;
    var path = '$cachePath/$name';
    return path;
  }
}

enum SourceType { net, asset }
